<template>
  <div class="config-page app-container">
    <div class="head">
      <div class="chunk title">
        <div class="product">组合信息</div>
      </div>
    </div>
    <div class="card card-first" v-loading="listLoading">
      <div class="flexLine">
        <div class="fromLine fromLine-text">
          <span class="label">组合名称：</span>
          <el-input
            :class="{ border_red: info.compositionName === '' }"
            v-model="info.compositionName"
            size="mini"
            :controls="false"
          ></el-input>
        </div>
        <div class="fromLine">
          <span class="label">投资金额：</span>
          <el-input
            :class="{ border_red: infoRuleList.initMoney }"
            style="width: 80px; margin-right: 4px"
            v-model="info.initMoney"
            size="mini"
            :controls="false"
            @change="checkAllInfoInitMoney"
          ></el-input>
          <span>万元</span>
        </div>
        <div class="fromLine">
          <span class="label">已用金额：</span>
          <el-input
            style="width: 80px; margin-right: 4px"
            v-model="compositionUseMonry"
            size="mini"
            :controls="false"
            disabled
          ></el-input>
          <span>万元</span>
        </div>
        <div class="fromLine">
          <span class="label">复利周期：</span>
          <el-select
            size="mini"
            v-model="info.warehouseAdjustmentCycle"
            placeholder="请选择"
            style="width: 120px"
          >
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="item in jczqList"
              :key="item.id"
            ></el-option>
          </el-select>
        </div>
        <div class="fromLine">
          <span class="label">开始日期：</span>
          <el-date-picker
            v-model="info.createdTime"
            size="mini"
            type="date"
            value-format="yyyy-MM-dd"
            :clearable="false"
            style="width: 160px; height: 24px"
            placeholder="开始时间"
          >
          </el-date-picker>
        </div>
      </div>
      <div class="flexLine">
        <div class="fromLine fromLine-text">
          <span class="label">添加备注：</span>
          <el-input
            v-model="info.mark"
            size="mini"
            :controls="false"
          ></el-input>
        </div>
        <div class="fromLine">
          <span class="label">固收年化：</span>
          <el-input
            style="width: 80px; margin-right: 4px"
            v-model="info.fixedIncome"
            size="mini"
            :controls="false"
          ></el-input>
          <span>%</span>
        </div>
        <div class="fromLine">
          <span class="label">名义金额：</span>
          <el-input
            style="width: 80px; margin-right: 4px"
            v-model="info.nominalAmount"
            size="mini"
            :controls="false"
            disabled
          ></el-input>
          <span>万元</span>
        </div>
        <div class="fromLine">
          <span class="label">复利方式：</span>
          <el-select
            clearable
            size="mini"
            v-model="info.compositionAccumulationType"
            placeholder="请选择"
            style="width: 120px"
            :disabled="info.warehouseAdjustmentCycle === 1"
          >
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="item in zhflfsList"
              :key="item.id"
            ></el-option>
          </el-select>
        </div>
        <div class="fromLine">
          <span class="label">对标指数：</span>
          <indexSelectTree
            :multiple="false"
            size="mini"
            :width="160"
            v-model="info.indexType"
          ></indexSelectTree>
        </div>
      </div>
    </div>
    <div class="head">
      <div class="chunk title">
        <div class="product">策略分类</div>
      </div>
    </div>
    <div
      class="card card-list"
      v-loading="listLoading"
      v-for="(items, i) in list1"
      :key="i"
    >
      <div class="card-list-title flexLine">
        <div class="fromLine">
          <span class="label">分类名称：</span>
          <el-input
            size="mini"
            :class="{ border_red: ruleList[i].classfyName }"
            v-model="items.classfyName"
            @input="checkClassfyName(i)"
            placeholder="请输入分类名称"
            style="width: 210px"
          ></el-input>
        </div>
        <div class="fromLine">
          <span class="label">投资金额：</span>
          <el-input
            :class="{ border_red: ruleList[i].investMoney }"
            size="mini"
            v-model="items.investMoney"
            :placeholder="remainingMoney"
            @change="checkInitMoney(i)"
            :controls="false"
            style="width: 90px; margin-right: 4px"
          ></el-input>
          <span>万元</span>
        </div>
        <div class="fromLine">
          <span class="label">已用金额：</span>
          <el-input
            size="mini"
            v-model="items.all_initialMoney"
            style="width: 80px; margin-right: 4px"
            disabled
          ></el-input>
          <span>万元</span>
        </div>
        <div class="fromLine">
          <span class="label">剩余金额：</span>
          <el-input
            size="mini"
            v-model="items.remainingSum"
            style="width: 80px; margin-right: 4px"
            disabled
          ></el-input>
          <span>万元</span>
        </div>
        <div class="fromLine">
          <span class="label">名义金额：</span>
          <el-input
            size="mini"
            v-model="items.nominalAmount"
            style="width: 80px; margin-right: 4px"
            disabled
          ></el-input>
          <span>万元</span>
        </div>
        <div class="fromLine">
          <span class="label">对标指数：</span>
          <indexSelectTree
            :class="{ border_red: ruleList[i].indexType }"
            :multiple="false"
            size="mini"
            :width="160"
            v-model="items.indexType"
          ></indexSelectTree>
        </div>
        <div
          v-show="list1.length > 1"
          @click="delectClassfyHandle(i)"
          class="btn del-btn"
        >
          <i class="iconfont icon-ashbin"></i>
          <span>删除分类</span>
        </div>
      </div>
      <div class="card-list-content">
        <div class="card-list-content-title">
          <div style="min-width: 40px; text-align: center">移动</div>
          <div style="min-width: 500px">策略名称</div>
          <div style="min-width: 120px">名义金额（万元）</div>
          <div style="min-width: 120px">杠杆率</div>
          <div style="min-width: 120px">投资金额（万元）</div>
          <div style="min-width: 180px">开始时间</div>
          <div style="min-width: 160px">复利方式</div>
          <div style="min-width: 120px">加仓单位（万元）</div>
          <div style="min-width: 100px">操作</div>
          <!--  flex-grow: 1 -->
        </div>
        <div class="list-table-content" :i="i" ref="listTableContent">
          <div
            class="list-content-row"
            v-for="(exItem, index) in items.classifyStrategyExt"
            :key="exItem.id"
          >
            <div
              class="handle-move"
              style="min-width: 40px; text-align: center"
            >
              <i class="iconfont icon-tuodongweizhi icon-move"></i>
            </div>
            <div style="min-width: 500px">
              <div
                style="display: inline-block"
                @click="selectStrategyHandle(i, index)"
              >
                <el-input
                  :class="{
                    strategyName: true,
                    border_red: ruleList[i].strategyName,
                  }"
                  size="mini"
                  @click="selectStrategyHandle(i, index)"
                  v-model="exItem.strategyName"
                  placeholder="请选择策略"
                  clearable
                  readonly
                >
                  <i
                    slot="suffix"
                    class="iconfont icon-arrow-right"
                    style="line-height: 28px"
                  ></i>
                </el-input>
              </div>
            </div>
            <div style="min-width: 120px">
              <el-input
                :class="{
                  border_red: exItem.ruleList.nominalAmount,
                }"
                size="mini"
                v-model="exItem.nominalAmount"
                :placeholder="remainingStrategyMoney(i, index)"
                @input="checkAmountHandle(i, index)"
                :controls="false"
                style="width: 100px"
              ></el-input>
            </div>
            <div style="min-width: 120px">
              <el-input
                :class="{
                  border_red: exItem.ruleList.leverageRatio,
                }"
                size="mini"
                v-model="exItem.leverageRatio"
                @input="checkLeverageRatio(i, index)"
                :controls="false"
                style="width: 100px"
              ></el-input>
            </div>
            <div style="min-width: 120px">
              <el-input
                :class="{
                  border_red: exItem.ruleList.initialMoney,
                }"
                size="mini"
                v-model="exItem.initialMoney"
                @input="checkInitialMoneyHandle(i, index)"
                :placeholder="remainingInitialMoney(i)"
                :controls="false"
                style="width: 100px"
              ></el-input>
            </div>
            <div style="min-width: 180px">
              <el-date-picker
                :class="{
                  border_red: ruleList[i].enterTime,
                }"
                v-model="exItem.enterTime"
                size="mini"
                type="date"
                @change="enterTimeChange($event, i, index)"
                value-format="yyyy-MM-dd"
                style="width: 160px"
                placeholder="请选择开始时间"
              >
              </el-date-picker>
            </div>
            <div style="min-width: 160px">
              <el-select
                size="mini"
                v-model="exItem.strategyAccumulationType"
                placeholder="请选择"
                style="width: 140px"
                :disabled="info.warehouseAdjustmentCycle === 1"
              >
                <el-option
                  :label="fitem.name"
                  :value="fitem.id"
                  v-for="fitem in flfsList"
                  :key="fitem.id"
                ></el-option>
              </el-select>
            </div>
            <div style="min-width: 120px">
              <el-input
                size="mini"
                @input="checkMinCycleEquityHandle(i, index)"
                v-model="exItem.minWarehouseAdjustmentCycleEquity"
                style="width: 100px"
                :disabled="exItem.strategyAccumulationType !== 2"
              ></el-input>
            </div>
            <div style="min-width: 100px">
              <!--  flex-grow: 1 -->
              <div class="btn del-btn" @click="delectStrategyHandle(i, index)">
                <i class="iconfont icon-ashbin"></i>
                <span>删除</span>
              </div>
            </div>
          </div>
        </div>

        <div class="btn add-btn" @click="selectStrategyHandle(i, 0, 'add')">
          <i class="iconfont icon-add-circle"></i>
          <span>添加策略</span>
        </div>
      </div>
    </div>
    <div class="btn add-btn-type" @click="addClassfyHandle">
      <i class="iconfont icon-add-circle"></i>
      <span>添加分类</span>
    </div>
    <div class="footer">
      <el-button
        size="small"
        style="font-size: 16px"
        :loading="saveLoading"
        @click="saveHandle(1)"
      >
        预览
      </el-button>
      <el-button
        type="primary"
        size="small"
        :loading="saveLoading"
        style="font-size: 16px"
        @click="saveHandle(2)"
      >
        保存
      </el-button>
    </div>

    <strategyOpen
      v-if="strategyVisible"
      ref="strategyOpen"
      :title="diaLogTitle"
      :type="tableType"
      :nolink="true"
      :userId="userId"
      @selctInvestName="selctInvestNameHandle"
      @selCheckctInvestName="selCheckctInvestNameHandle"
    ></strategyOpen>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { Sortable } from "sortablejs";
import {
  getCompositionAndClassifysByCompositionId,
  configComposition,
} from "@/api/combManage";
import indexSelectTree from "@/components/investComn/indexSelectTree.vue";
import strategyOpen from "@/views/afterManage/afterInvest/relation/strategyOpen.vue";
import { parseTime } from "@/utils";
import { JCZQ_OPTIONS, FLFS_OPTIONS, ZHFLFS_OPTIONS } from "./const";

export default {
  name: "StrategyCombManageConfig",
  components: {
    strategyOpen,
    indexSelectTree,
  },
  data() {
    return {
      strategyVisible: false,
      strategy_i: undefined,
      strategy_index: undefined,
      compositionUseMonry: 0,
      compositionId: "",
      listLoading: false,
      info: {},
      list1: [],
      ruleList: [],
      infoRuleList: {
        initMoney: false,
      },
      jczqList: JCZQ_OPTIONS,
      flfsList: FLFS_OPTIONS,
      zhflfsList: ZHFLFS_OPTIONS,
      saveLoading: false,
      diaLogTitle: "更改策略（单选）",
      tableType: "radio",
    };
  },
  created() {
    this.compositionId = this.$route.query.compositionId;
    if (this.$route.query.type === "created") {
      this.createdConfig();
    } else {
      this.getInfo();
    }
  },
  watch: {
    WatchwarehouseAdjustmentCycle(val, old) {
      // console.log(old, val);
      for (let i = 0; i < this.list1.length; i++) {
        for (let n = 0; n < this.list1[i].classifyStrategyExt.length; n++) {
          // let strategyAccumulationType = "";
          if (val === 1) {
            this.info.compositionAccumulationType = "";
            // strategyAccumulationType = 1;
            this.$set(
              this.list1[i].classifyStrategyExt[n],
              "minWarehouseAdjustmentCycleEquity",
              ""
            );
          }
          // else {
          //   strategyAccumulationType =
          //     old === 1
          //       ? ""
          //       : this.list1[i].classifyStrategyExt[n].strategyAccumulationType;
          // }
          // this.$set(
          //   this.list1[i].classifyStrategyExt[n],
          //   "strategyAccumulationType",
          //   strategyAccumulationType
          // );
        }
      }
    },
  },
  mounted() {
    // this.rowDrop();
  },
  activated() {
    if (this.compositionId != this.$route.query.compositionId) {
      this.compositionId = this.$route.query.compositionId;
      if (this.$route.query.type === "created") {
        this.createdConfig();
      } else {
        this.getInfo();
      }
    }
  },
  computed: {
    ...mapGetters(["userId", "createComb"]),
    // 剩余投资金额
    remainingMoney: function() {
      let money = this.info.initMoney;
      for (let i = 0; i < this.list1.length; i++) {
        money = this.fomatFloat(money - this.list1[i].investMoney);
      }
      money = money >= 0 ? money : 0;
      return "最多" + money;
    },
    // 策略剩余名义金额
    remainingStrategyMoney: function() {
      return (i, index) => {
        let money = this.list1[i].initialMoney;
        for (let n = 0; n < this.list1[i].classifyStrategyExt.length; n++) {
          money = this.fomatFloat(
            money - this.list1[i].classifyStrategyExt[n].initialMoney
          );
        }
        money = this.fomatFloat(
          this.list1[i].classifyStrategyExt[index].leverageRatio * money
        );
        money = money >= 0 ? money : 0;
        return "最多" + money;
      };
    },
    // 策略剩余投资金额
    remainingInitialMoney: function() {
      return (i) => {
        let money = this.list1[i].initialMoney;
        for (let n = 0; n < this.list1[i].classifyStrategyExt.length; n++) {
          money = this.fomatFloat(
            money - this.list1[i].classifyStrategyExt[n].initialMoney
          );
        }
        money = money >= 0 ? money : 0;
        return "最多" + money;
      };
    },
    //
    WatchwarehouseAdjustmentCycle: function() {
      return this.info.warehouseAdjustmentCycle;
    },
  },
  methods: {
    enterTimeChange(date, i, index) {
      if (new Date(date) <= new Date(this.info.createdTime)) {
        this.info.createdTime = date;
      } else {
        let res_date = "";
        this.list1.map((items) => {
          items.classifyStrategyExt.map((item) => {
            if (!res_date) {
              res_date = item.enterTime;
            } else if (new Date(item.enterTime) < new Date(res_date)) {
              res_date = item.enterTime;
            }
          });
        });
        this.info.createdTime = res_date;
      }
    },
    // 过滤非数字
    checkNumber(value) {
      value = value.toString();
      value = value.replace(/[^\d.]/g, "");
      value = value.replace(/^\./g, "");
      value = value.replace(/\.{2,}/g, ".");
      value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
      return +value;
    },
    // 总投资金额校验infoInitMoney
    checkAllInfoInitMoney() {
      this.info.initMoney = this.checkNumber(this.info.initMoney);
      this.$message.closeAll();
      let n = 0;
      this.list1.map((item) => {
        n += parseInt(item.initMoney);
      });
      if (n > this.info.initMoney) {
        this.$nextTick(() => {
          this.infoRuleList.initMoney = true;
          this.$message.closeAll();
          this.$message({
            message: "分类总投资金额已超过组合投资金额",
            type: "warning",
          });
        });
      } else {
        for (let i = 0; i < this.list1.length; i++) {
          this.checkInitMoney(i);
        }
      }
    },

    // 分类名称校验
    checkClassfyName(i) {
      if (this.list1[i].classfyName) {
        this.$set(this.ruleList[i], "classfyName", false);
      }
    },
    // 投资金额验证
    checkInitMoney(i) {
      this.$set(
        this.list1[i],
        "investMoney",
        this.checkNumber(this.list1[i].investMoney)
      );

      this.$message.closeAll();
      let n = 0;
      this.list1.map((item) => {
        n += parseInt(item.investMoney);
      });
      let m = 0;
      this.list1[i].classifyStrategyExt.map((item) => {
        m += parseInt(item.initialMoney);
      });
      if (n > this.info.initMoney) {
        this.$nextTick(() => {
          this.$set(this.ruleList[i], "investMoney", true);
          this.$message.closeAll();
          this.$message({
            message: "分类总投资金额已超过组合投资金额",
            type: "warning",
          });
        });
      } else if (this.list1[i].investMoney < m) {
        this.$nextTick(() => {
          this.$set(this.ruleList[i], "investMoney", true);
          this.$message({
            message: "策略总投资金额已超过该分类投资金额",
            type: "warning",
          });
        });
      } else {
        // 组合资金/策略分类资金/策略资金校验/剩余金额 重置
        this.calculateNum(i);
        this.infoRuleList.initMoney = false;
        this.$set(this.ruleList[i], "investMoney", false);
        this.setClassifyStrategyExtRuleList(i, "leverageRatio", false);
        this.setClassifyStrategyExtRuleList(i, "initialMoney", false);
        this.setClassifyStrategyExtRuleList(i, "nominalAmount", false);
        return true;
      }
    },
    // 名义金额校验
    checkAmountHandle(i, index) {
      this.$set(
        this.list1[i].classifyStrategyExt[index],
        "nominalAmount",
        this.checkNumber(this.list1[i].classifyStrategyExt[index].nominalAmount)
      );
      // 计算投资金额
      this.$set(
        this.list1[i].classifyStrategyExt[index],
        "initialMoney",
        this.fomatFloat(
          this.list1[i].classifyStrategyExt[index].nominalAmount /
            this.list1[i].classifyStrategyExt[index].leverageRatio
        )
      );
      this.$message.closeAll();
      const all_cl_initialMoney = this.calculateNum(i, "nominalAmount");

      if (
        all_cl_initialMoney > this.list1[i].investMoney ||
        this.list1[i].classifyStrategyExt[index].nominalAmount === 0
      ) {
        this.$nextTick(() => {
          this.$set(
            this.list1[i].classifyStrategyExt[index].ruleList,
            "nominalAmount",
            true
          );
          if (all_cl_initialMoney > this.list1[i].investMoney) {
            this.$message({
              message: "策略总投资金额已超过该分类投资金额",
              type: "warning",
            });
          }
        });
      } else {
        this.checkInitMoney(i);
      }
    },
    // 杠杆率校验
    checkLeverageRatio(i, index) {
      this.$set(
        this.list1[i].classifyStrategyExt[index],
        "leverageRatio",
        this.checkNumber(this.list1[i].classifyStrategyExt[index].leverageRatio)
      );
      // 计算投资金额
      this.$set(
        this.list1[i].classifyStrategyExt[index],
        "initialMoney",
        this.fomatFloat(
          this.list1[i].classifyStrategyExt[index].nominalAmount /
            this.list1[i].classifyStrategyExt[index].leverageRatio
        )
      );
      this.$message.closeAll();
      const all_cl_initialMoney = this.calculateNum(i);
      if (
        all_cl_initialMoney > this.list1[i].investMoney ||
        this.list1[i].classifyStrategyExt[index].leverageRatio === 0
      ) {
        this.$nextTick(() => {
          this.$set(
            this.list1[i].classifyStrategyExt[index].ruleList,
            "leverageRatio",
            true
          );
          if (all_cl_initialMoney > this.list1[i].investMoney) {
            this.$message({
              message: "策略总投资金额已超过该分类投资金额",
              type: "warning",
            });
          }
        });
      } else {
        this.checkInitMoney(i);
      }
    },
    // 投资金额校验
    checkInitialMoneyHandle(i, index) {
      this.$set(
        this.list1[i].classifyStrategyExt[index],
        "initialMoney",
        this.checkNumber(this.list1[i].classifyStrategyExt[index].initialMoney)
      );
      // 计算名义金额
      this.$set(
        this.list1[i].classifyStrategyExt[index],
        "nominalAmount",
        this.fomatFloat(
          this.list1[i].classifyStrategyExt[index].initialMoney *
            this.list1[i].classifyStrategyExt[index].leverageRatio
        )
      );
      this.$message.closeAll();
      const all_cl_initialMoney = this.calculateNum(i);
      this.$nextTick(() => {
        if (
          all_cl_initialMoney > this.list1[i].investMoney ||
          this.list1[i].classifyStrategyExt[index].initialMoney === 0
        ) {
          this.$set(
            this.list1[i].classifyStrategyExt[index].ruleList,
            "initialMoney",
            true
          );
          if (all_cl_initialMoney > this.list1[i].investMoney) {
            this.$message({
              message: "策略总投资金额已超过该分类投资金额",
              type: "warning",
            });
          }
        } else {
          this.checkInitMoney(i);
        }
      });
    },
    checkMinCycleEquityHandle(i, index) {
      this.$set(
        this.list1[i].classifyStrategyExt[index],
        "minWarehouseAdjustmentCycleEquity",
        this.checkNumber(
          this.list1[i].classifyStrategyExt[index]
            .minWarehouseAdjustmentCycleEquity
        )
      );
    },
    calculateNum(i, type) {
      let all_cl_initialMoney = 0;
      let all_cl_nominalAmount = 0;
      let all_nominalAmount = 0;
      let all_initialMoney = 0;
      this.list1[i].classifyStrategyExt.map((item) => {
        all_cl_initialMoney += this.fomatFloat(item.initialMoney);
        all_cl_nominalAmount += this.fomatFloat(item.nominalAmount);
      });
      this.$set(
        this.list1[i],
        "all_initialMoney",
        this.fomatFloat(all_cl_initialMoney)
      );
      this.$set(
        this.list1[i],
        "nominalAmount",
        this.fomatFloat(all_cl_nominalAmount)
      );
      this.$set(
        this.list1[i],
        "remainingSum",
        this.fomatFloat(this.list1[i].investMoney - all_cl_initialMoney)
      );

      this.list1.map((item) => {
        all_initialMoney += this.fomatFloat(item.all_initialMoney);
        all_nominalAmount += this.fomatFloat(item.nominalAmount);
      });
      this.compositionUseMonry = this.fomatFloat(all_initialMoney);
      this.info.nominalAmount = this.fomatFloat(all_nominalAmount);
      return all_cl_initialMoney;
    },
    setRuleList(className, data) {
      for (let i = 0; i < this.ruleList.length; i++) {
        this.$set(this.ruleList[i], className, data);
      }
    },
    setClassifyStrategyExtRuleList(n, className, data) {
      for (let i = 0; i < this.list1[n].classifyStrategyExt.length; i++) {
        this.$set(
          this.list1[n].classifyStrategyExt[i].ruleList,
          className,
          data
        );
      }
    },
    fomatFloat(src, pos) {
      pos = pos || 2;
      src = src !== Infinity ? src : 0;
      return Math.round(src * Math.pow(10, pos)) / Math.pow(10, pos) || 0;
    },
    addClassfyHandle() {
      this.initRuleList("add");
      this.list1.push({
        createdBy: this.userId,
        compositionId: this.compositionId,
        classfyName: "",
        nominalAmount: "-",
        initMoney: this.checkNumber(this.remainingMoney),
        investMoney: this.checkNumber(this.remainingMoney),
        remainingSum: "-",
        all_initialMoney: "-",
        classifyStrategyExt: [],
        indexType: undefined,
        createdTime: parseTime(new Date()),
      });
      this.rowDrop();
    },
    delectClassfyHandle(i) {
      this.$confirm(
        `确认删除分类名称【${this.list1[i].classfyName}】此条数据？`,
        "提示",
        {
          type: "warning",
        }
      )
        .then((_) => {
          this.list1.splice(i, 1);
          this.initRuleList(i);
        })
        .catch((_) => {});
    },
    delectStrategyHandle(i, index) {
      this.$confirm(
        `确认删除策略名称【${this.list1[i].classifyStrategyExt[index].strategyName}】此条数据？`,
        "提示",
        {
          type: "warning",
        }
      )
        .then((_) => {
          this.list1[i].classifyStrategyExt.splice(index, 1);
          this.calculateNum(i);
          let res_date = "";
          this.list1.map((items) => {
            items.classifyStrategyExt.map((item) => {
              if (!res_date) {
                res_date = item.enterTime;
              } else if (new Date(item.enterTime) < new Date(res_date)) {
                res_date = item.enterTime;
              }
            });
          });
          this.info.createdTime = res_date;
        })
        .catch((_) => {});
    },
    selctInvestNameHandle(strategyInfoVo) {
      this.list1[this.strategy_i].classifyStrategyExt[
        this.strategy_index
      ].strategyId = strategyInfoVo.strategyId;
      this.list1[this.strategy_i].classifyStrategyExt[
        this.strategy_index
      ].strategyName = strategyInfoVo.strategyName;
      this.list1[this.strategy_i].classifyStrategyExt[
        this.strategy_index
      ].enterTime = strategyInfoVo.makeTime;
      if (new Date(strategyInfoVo.makeTime) < new Date(this.info.createdTime)) {
        this.info.createdTime = strategyInfoVo.makeTime;
      }
    },
    selCheckctInvestNameHandle(checkList) {
      for (var i = 0; i < checkList.length; i++) {
        this.list1[this.strategy_i].classifyStrategyExt.push({
          strategyId: checkList[i].strategyInfoVo.strategyId,
          leverageRatio: 1,
          initialMoney: "",
          enterTime: checkList[i].strategyInfoVo.makeTime,
          strategyName: checkList[i].strategyInfoVo.strategyName,
          strategyAccumulationType: 1,
          ruleList: {
            AllInfoInitMoney: false,
            nominalAmount: false,
            leverageRatio: false,
            initialMoney: false,
          },
        });
        if (
          new Date(checkList[i].strategyInfoVo.makeTime) <
          new Date(this.info.createdTime)
        ) {
          this.info.createdTime = checkList[i].strategyInfoVo.makeTime;
        }
      }
    },
    selectStrategyHandle(i, index, type) {
      this.strategy_i = i;
      this.strategy_index = index;
      this.strategyVisible = true;
      if (type === "add") {
        this.diaLogTitle = "选择策略（可多选）";
        this.tableType = "check";
      } else {
        this.tableType = "radio";
        this.diaLogTitle = "更改策略（单选）";
      }
      this.$nextTick(() => {
        this.$refs.strategyOpen.init();
      });
    },
    getInfo() {
      this.listLoading = true;
      getCompositionAndClassifysByCompositionId({
        compositionId: this.compositionId,
      }).then((res) => {
        this.listLoading = false;
        // 设置默认值，后端增加字段后可删除
        res.body.strategyCompositionVo.warehouseAdjustmentCycle =
          res.body.strategyCompositionVo.warehouseAdjustmentCycle || 1;

        this.info = res.body.strategyCompositionVo;
        this.list1 = res.body.strategyClassifyVo.map((item) => {
          const classifyStrategyExt = item.classifyStrategyExt;
          const data = {
            classfyName: item.classfyName,
            compositionId: item.compositionId,
            classifyId: item.classifyId,
            initMoney: item.initMoney,
            investMoney: item.investMoney || 0,
            createdBy: item.createdBy,
            createdTime: item.createdTime,
            indexType: item.indexType,
            all_initialMoney: 0, // 已用金额
            nominalAmount: 0, // 名义金额
            remainingSum: 0, //剩余金额
          };
          data.classifyStrategyExt = classifyStrategyExt.map((mitem) => {
            mitem = {
              strategyId: mitem.strategyId,
              strategyName: mitem.strategyName,
              initialMoney: mitem.initialMoney, // 策略投资金额
              nominalAmount: mitem.nominalAmount, // 策略名义金额
              enterTime: mitem.enterTime,
              leverageRatio: mitem.leverageRatio, //策略杠杆率
              minWarehouseAdjustmentCycleEquity:
                mitem.minWarehouseAdjustmentCycleEquity || "", //最小加仓金额
              strategyAccumulationType: mitem.strategyAccumulationType, //策略复利方式

              ruleList: { nominalAmount: false },
            };
            mitem.nominalAmount = this.fomatFloat(
              mitem.initialMoney * mitem.leverageRatio
            );
            data.all_initialMoney += this.fomatFloat(mitem.initialMoney);
            data.nominalAmount += this.fomatFloat(mitem.nominalAmount);
            return mitem;
          });
          data.remainingSum = this.fomatFloat(
            data.investMoney - data.all_initialMoney
          );
          this.compositionUseMonry = data.all_initialMoney;
          return data;
        });
        // this.list1.map((item, i) => {
        //   this.classfyUseMoneyHandle(i);
        // });
        console.log(this.list1);
        this.initRuleList();
        this.rowDrop();
      });
    },
    initRuleList(type, i) {
      if (type === "add") {
        this.ruleList.push({
          initMoney: false,
          investMoney: false,
          classfyName: false,
        });
      } else if (i) {
        this.ruleList.splice(i, 1);
      } else {
        this.ruleList = [];
        for (let i = 0; i < this.list1.length; i++) {
          this.ruleList.push({
            initMoney: false, //分类剩余金额
            investMoney: false,
            classfyName: false,
          });
        }
      }
    },
    saveHandle(goDetailPage) {
      // 校验
      this.checkAllInfoInitMoney();
      let check = true;
      let noEmpty = false;
      let noMoney = false;
      let checkInfoInitMoney = 0;
      if (this.info.compositionName === "") {
        noEmpty = true;
      }
      this.ruleList.map((item) => {
        if (item.investMoney) {
          noMoney = true;
        }
      });
      for (let i = 0; i < this.list1.length; i++) {
        const obj = this.list1[i];
        checkInfoInitMoney += this.fomatFloat(obj.investMoney);
        if (checkInfoInitMoney > this.info.initMoney) {
          noMoney = "分类总投资金额已超过组合投资金额";
          return;
        }
        if (obj.classfyName == this.info.compositionName) {
          this.$message({
            message: "分类名称不能和组合名称相同",
            type: "warning",
          });
          check = false;
          return;
        }
        if (!obj.classfyName) {
          this.$set(this.ruleList[i], "classfyName", true);
          noEmpty = true;
        }
        if (obj.classifyStrategyExt.length === 0) {
          this.$message({
            message: "策略分类最少需要一条配置策略",
            type: "warning",
          });
          return;
        }
        let investMoneyAll = 0;
        for (let j = 0; j < obj.classifyStrategyExt.length; j++) {
          const o = obj.classifyStrategyExt[j];
          investMoneyAll += this.fomatFloat(o.initialMoney);
          if (investMoneyAll > o.investMoney) {
            noMoney = "策略总投资金额已超过该分类投资金额";
            return;
          }
          if (!o.initialMoney) {
            this.$set(o.ruleList, "initialMoney", true);
            noEmpty = true;
          }
          if (!o.nominalAmount) {
            this.$set(o.ruleList, "nominalAmount", true);
            noEmpty = true;
          }
          if (!o.strategyName) {
            this.$set(o.ruleList, "strategyName", true);
            noEmpty = true;
          }
          if (!o.leverageRatio) {
            this.$set(o.ruleList, "leverageRatio", true);
          }
          if (
            o.ruleList.initialMoney ||
            o.ruleList.nominalAmount ||
            o.ruleList.leverageRatio
          ) {
            noMoney = "策略总投资金额已超过该分类投资金额";
          }
        }
      }

      console.log("222");
      if (!check) return;
      if (noEmpty) {
        this.$message({
          message: "存在未填项",
          type: "warning",
        });
        return;
      }
      console.log(noMoney);
      if (noMoney) {
        // this.$message({
        //   message: noMoney,
        //   type: "warning",
        // });
        return;
      }
      this.saveLoading = true;
      const data = this.list1.map((item) => {
        const classifyStrategyExt = item.classifyStrategyExt;
        item = {
          classfyName: item.classfyName, // 分类名称
          compositionId: item.compositionId,
          classifyId: item.classifyId,
          initMoney: item.all_initialMoney, // 分类占用金额
          createdBy: item.createdBy,
          createdTime: item.createdTime,
          indexType: item.indexType, //对标指数
          investMoney: item.investMoney, // 分类投资金额
          nominalAmount: item.nominalAmount, // 分类名义金额
        };
        item.classifyStrategyExt = classifyStrategyExt.map((mitem) => {
          mitem = {
            strategyId: mitem.strategyId,
            strategyName: mitem.strategyName,
            initialMoney: mitem.initialMoney, // 策略投资金额
            currentMoney: mitem.initialMoney,
            enterTime: mitem.enterTime,
            leverageRatio: mitem.leverageRatio, //策略杠杆率
            minWarehouseAdjustmentCycleEquity: this.fomatFloat(
              mitem.minWarehouseAdjustmentCycleEquity
            ), //组合最小加仓金额
            strategyAccumulationType: mitem.strategyAccumulationType || "", //策略复利方式 1不复利 2与组合周期相同 3单独复利
          };
          return mitem;
        });
        return item;
      });
      configComposition({
        strategyCompositionVo: {
          createdBy: this.userId,
          warehouseAdjustmentCycle: this.info.warehouseAdjustmentCycle,
          compositionAccumulationType:
            this.info.compositionAccumulationType || 1, // 组合复利方式  1全组合复利 2按策略复利
          compositionId: this.info.compositionId,
          createdTime: this.info.createdTime,
          nominalAmount: this.info.nominalAmount,
          initMoney: this.info.initMoney,
          fixedIncome: this.info.fixedIncome,
          compositionName: this.info.compositionName,
          mark: this.info.mark,
          indexType: this.info.indexType,
        },
        // "compositionId": 198,
        // "createdTime": "2022-03-03",
        // "nominalAmount": 20,
        // "initMoney": 100,
        // "fixedIncome": 5,
        // "warehouseAdjustmentCycle": 1,
        // "compositionAccumulationType": 1
        strategyClassifyVo: data,
      })
        .then((res) => {
          this.saveLoading = false;
          if (res.code == 0) {
            if (goDetailPage == 1) {
              this.$notify({
                message: res.body,
                type: "success",
                duration: 2000,
              });
              this.$router.push({
                path: `/strategyComb/combManage/netWorthAnalysis/${this.compositionId}`,
              });
            } else if (goDetailPage == 2) {
              this.$notify({
                message: res.body,
                type: "success",
                duration: 2000,
              });
              this.$store.dispatch("tagsView/delView", this.$route);
              this.$router.push("/strategyComb/combManage");
            }
          }
        })
        .catch(() => {
          this.saveLoading = false;
        });
    },
    warehouseAdjustmentCycleChange() {},
    // 行拖拽
    rowDrop() {
      this.$nextTick(() => {
        var listHtmlArr = this.$refs.listTableContent;
        for (var i = 0; i < listHtmlArr.length; i++) {
          const listHtml = listHtmlArr[i];
          new Sortable(listHtml, {
            group: "shared",
            animation: 150,
            chosenClass: "chosen",
            handle: ".handle-move",
            onEnd: (evt) => {
              // 还原 Sortable 的DOM操作
              const newIndex = evt.newIndex;
              const oldIndex = evt.oldIndex;
              const $li = evt.to.children[newIndex];
              const $oldli = evt.from.children[oldIndex];
              // console.log($li);
              if (evt.to !== evt.from) {
                evt.to.removeChild($li);
                evt.from.insertBefore($li, $oldli);
              }
              // 修改移动后的数据对象，自动更新视图
              const fromi = evt.from.getAttribute("i");
              const toi = evt.to.getAttribute("i");
              const row = this.list1[fromi].classifyStrategyExt[evt.oldIndex];
              this.list1[fromi].classifyStrategyExt.splice(evt.oldIndex, 1);
              this.list1[toi].classifyStrategyExt.splice(evt.newIndex, 0, row);
              this.checkInitMoney(toi);
            },
          });
          this.checkInitMoney(i);
        }
      });
    },
    // 创建新配置组合
    createdConfig() {
      this.listLoading = false;

      const strategyCompositionVo =
        this.createComb[this.compositionId].strategyCompositionVo;
      this.info = {
        warehouseAdjustmentCycle: 1,
        compositionAccumulationType: 1, // 组合复利方式  1全组合复利 2按策略复利
        compositionId: strategyCompositionVo.compositionId,
        compositionName: strategyCompositionVo.compositionName,
        createdTime: strategyCompositionVo.createdTime,
        nominalAmount: strategyCompositionVo.nominalAmount || 0,
        initMoney: strategyCompositionVo.initMoney || 0,
        fixedIncome: strategyCompositionVo.fixedIncome,
      };
      const strategyClassifyVo =
        this.createComb[this.compositionId].strategyClassifyVo;
      const data = {
        classfyName: strategyClassifyVo[0].classfyName,
        compositionId: strategyClassifyVo[0].compositionId,
        classifyId: strategyClassifyVo[0].classifyId,
        initMoney: strategyClassifyVo[0].initMoney,
        createdBy: strategyClassifyVo[0].createdBy,
        createdTime: strategyClassifyVo[0].createdTime,
        indexType: strategyClassifyVo[0].indexType,
        investMoney: strategyClassifyVo[0].investMoney || 0,
        all_initialMoney: 0, // 已用金额
        nominalAmount: 0, // 名义金额
        remainingSum: 0, //剩余金额
      };
      data.classifyStrategyExt = strategyClassifyVo[0].classifyStrategyExt.map(
        (item) => {
          // console.log(this.info);
          if (+new Date(item.enterTime) < +new Date(this.info.createdTime)) {
            this.info.createdTime = item.enterTime;
          }
          const row = {
            strategyId: item.strategyId,
            strategyName: item.strategyName,
            initialMoney: item.initialMoney, // 策略投资金额
            nominalAmount: item.nominalAmount, // 策略名义金额
            enterTime: item.enterTime,
            leverageRatio: item.leverageRatio, // 策略杠杆率
            strategyAccumulationType: 1, // 默认不复利
            minWarehouseAdjustmentCycleEquity:
              item.minWarehouseAdjustmentCycleEquity,
            ruleList: {
              nominalAmount: false,
            },
          };
          return row;
        }
      );
      this.list1 = [];
      this.ruleList = [];
      this.ruleList.push({
        initMoney: false, //分类剩余金额
        classfyName: false,
      });
      console.log(data);
      this.list1.push(data);
    },
  },
};
</script>

<style lang="scss" scoped>
// 公共样式
.app-container {
  background: #f5f5f5;
}
.fromLine {
  min-width: 190px;
  .label {
    min-width: unset;
  }
}

.btn {
  width: 88px;
  height: 28px;
  white-space: nowrap;
  line-height: 26px;
  background: #ffffff;
  color: #666666;
  border: 1px solid #dcdfe6;
  border-radius: 5px;
  transition: all 0.2s;
  cursor: pointer;
  .iconfont {
    margin: 0 4px;
  }
  &:hover {
    color: #1890ff;
    border: 1px solid #1890ff;
  }
}

.config-page {
  .card {
    font-size: 14px;
    margin: 16px 0 24px 0;
    background: #ffffff;
    box-shadow: 0px 3px 9px 0px rgba(0, 0, 0, 0.05);
    border-radius: 5px;
    min-height: 80px;
    padding: 16px;
    padding-bottom: 0;
    overflow-x: auto;
    .flexLine {
      display: flex;
      justify-content: space-between;
      margin-bottom: 16px;
      margin-right: 40px;
      .fromLine-text {
        .el-input {
          width: 400px;
        }
      }
    }
    .content {
      min-width: 1300px;
    }
    .list1-card {
      margin-top: 10px;
    }
    .list2-card {
      margin-top: 10px;
    }
    .card-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 6px 10px;
      div {
        width: 30%;
      }
      .short {
        width: 80px;
      }
      .width25 {
        width: 25%;
      }
      .width20 {
        width: 20%;
      }
      // .name-money {width: 25%;}
      // .leverageRatio {width: 25%;}
      .label {
        padding-right: 10px;
      }
      .iconGrounp {
        width: 150px;
        .icon {
          font-size: 18px;
          font-weight: bold;
          cursor: pointer;
          & + .icon {
            margin-left: 10px;
          }
        }
        .el-icon-close,
        .el-icon-remove {
          font-size: 20px;
          color: red;
        }
        .el-icon-plus,
        .el-icon-circle-plus {
          font-size: 20px;
          color: #0af;
        }
      }
    }
    .card1-content {
      background: rgb(220, 237, 255);
    }
    .card2-content {
      border: 1px solid #eee;
      border-radius: 4px;
    }
    .strategyName {
      width: 460px;
    }
    .icon-move {
      cursor: pointer;
      font-size: 21px;
      width: 40px;
      display: inline-block;
      line-height: 28px;
    }
  }
  .card-list {
    padding: 0;
    // .flexLine {
    //   display: flex;
    //   justify-content: space-between;
    //   margin-bottom: 16px;
    // }
    .card-list-title {
      display: flex;
      justify-self: start;
      background: #e6eefa;
      margin: 0;
      padding: 10px 16px;
      line-height: 28px;
    }
    .card-list-content {
      margin: 12px 16px;
      .add-btn {
        margin-top: 12px;
        width: 100%;
        height: 40px;
        line-height: 38px;
        background: #ffffff;
        border-radius: 5px;
        text-align: center;
        border: 1px dashed #d9d9d9;
        &:hover {
          border-color: #1890ff;
        }
      }
      .del-btn {
        width: 60px;
      }
      &-title {
        display: flex;
        background: #f5f7fa;
        color: #666;
        font-weight: bold;
        line-height: 37px;
        justify-content: space-between;
        border-bottom: 1px solid #ebeef5;
        div {
          display: inline-block;
        }
      }
      .list-content-row {
        margin-top: 6px;
        padding-bottom: 6px;
        display: flex;
        border-bottom: 1px solid #ebeef5;
        justify-content: space-between;
      }
      .chosen {
        padding-top: 6px;
        background: #fff;
        border: 1px solid #40a9ff;
        box-shadow: 0px 0px 7px 3px rgba(0, 0, 0, 0.15);
      }
    }
  }
  .add-btn-type {
    width: 100%;
    height: 40px;
    line-height: 38px;
    background: #ffffff;
    text-align: center;
    box-shadow: 0px 3px 9px 0px rgba(0, 0, 0, 0.05);
    font-weight: bold;
    font-size: 18px;
    border: 0;
    .iconfont {
      font-size: 18px;
      margin: 0 5px;
    }
    &:hover {
      border: 0;
    }
  }
  .footer {
    margin-top: 60px;
    text-align: right;
    padding-right: 40px;
    ::v-deep .el-button {
      width: 160px;
      height: 40px;
    }
  }

  .head {
    .title {
      .product {
        font-size: 20px;
        font-weight: bold;
        color: rgba(0, 0, 0, 0.75);
        line-height: 28px;
      }
    }
  }
}
</style>

